﻿using FutianCloudAPIService.Utils;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;

namespace FutianCloudAPIService.Domains.Hanvon
{
    public class HanvonApi
    {
        private static string key = "05837332-1f34-4571-a033-4638667319e8";
        private static string code = "91f6a58d-e418-4e58-8ec2-61b583c55ba2";
        private static string hanurl = "http://api.hanvon.com/rt/ws/v1/ocr/bcard/recg";
        private static string uid = "127.0.0.1";
        private static string lang = "chns";
        private static string color = "gray";

        public HanvonApi()
        {

        }

        #region Business card

        /// <summary>
        /// 识别名片
        /// </summary>
        /// <param name="imagePath">本地路径</param>
        /// <returns>返回识别的json</returns>
        public static string Recognize(string imagePath)
        {
            using (Bitmap img = (Bitmap)Image.FromFile(imagePath))
            {
                return Recognize(img);
            }
        }

        /// <summary>
        /// 识别名片
        /// </summary>
        /// <param name="bmp">图片</param>
        /// <returns>返回识别的json</returns>
        public static string Recognize(Bitmap bmp)
        {
            using (var b = ImageUtil.ToGray(bmp))
            {
                var base64String = ImageUtil.ImgToBase64(bmp);

                return PostRecognizeCard(base64String);
            }
        }

        /// <summary>
        /// 发送请求
        /// </summary>
        private static string PostRecognizeCard(string imageBase64)
        {
            var task = WebUtil.Post(hanurl
               , new[] { new KeyValuePair<string,object>("uid",uid)
                        , new KeyValuePair<string,object>("lang",lang)
                        , new KeyValuePair<string,object>("color",color)
                        , new KeyValuePair<string,object>("image",imageBase64)
               }
               , new[] { new KeyValuePair<string, string>("key", key)
                        , new KeyValuePair<string, string>("code", code)
               }
               , req => req.DefaultRequestHeaders.Accept.Add(
                   new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/octet-stream"))
           );

            return task.Result;
        }
        #endregion Business card
    }
}
